package com.marvels.financial.pay.hjpay.service.impl;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.marvels.common.constants.MarvelsConstant;
import com.marvels.common.dto.UserDTO;
import com.marvels.common.dto.pay.McfeRepaymentTradeDetails;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.BeanUtils;
import com.marvels.common.utils.CacheUtils;
import com.marvels.common.utils.DateUtils;
import com.marvels.common.utils.HttpUtils;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.ServerProperties;
import com.marvels.financial.consum.FinancialConsumerApproveApi;
import com.marvels.financial.consum.FinancialConsumerLoanApplyApi;
import com.marvels.financial.loan.dao.McfeCustomerLoanContractDao;
import com.marvels.financial.loan.dao.McfeLendingProcessDao;
import com.marvels.financial.loan.dao.McfePaymentWithholdDao;
import com.marvels.financial.loan.dao.McfePaymentWithholdDetailDao;
import com.marvels.financial.loan.dto.McamLoanApplyInfoDTO;
import com.marvels.financial.loan.dto.McfeCustomerLoanContractDTO;
import com.marvels.financial.loan.dto.McfeLendingProcess;
import com.marvels.financial.loan.dto.McfePaymentWithholdDTO;
import com.marvels.financial.loan.dto.McfePaymentWithholdDetailDTO;
import com.marvels.financial.loan.service.LoanAuditApi;
import com.marvels.financial.loan.service.LoanPaymentApi;
import com.marvels.financial.loan.service.WithholdPaymentApi;
import com.marvels.financial.pay.dao.McfeMerchantRechargeRecordMapper;
import com.marvels.financial.pay.dao.McfeRepaymentTradeDetailsMapper;
import com.marvels.financial.pay.dto.McfeMerchantRechargeRecordDTO;
import com.marvels.financial.pay.dto.MerchantRechargeCallBackDTO;
import com.marvels.financial.pay.hjpay.dto.AgreementPaymentDTO;
import com.marvels.financial.pay.hjpay.dto.AgreementPaymentQueryDTO;
import com.marvels.financial.pay.hjpay.dto.AgreementPaymentQueryResultDTO;
import com.marvels.financial.pay.hjpay.dto.AgreementPaymentResultDTO;
import com.marvels.financial.pay.hjpay.dto.AgreementPaymentSignDTO;
import com.marvels.financial.pay.hjpay.dto.AgreementPaymentSignResultDTO;
import com.marvels.financial.pay.hjpay.dto.AgreementPaymentSmsDTO;
import com.marvels.financial.pay.hjpay.dto.AgreementPaymentSmsResultDTO;
import com.marvels.financial.pay.hjpay.dto.AvailableBalanceResultDTO;
import com.marvels.financial.pay.hjpay.dto.AvailableBalanceResultDesirableDTO;
import com.marvels.financial.pay.hjpay.dto.DirectPaymentDTO;
import com.marvels.financial.pay.hjpay.dto.DirectPaymentQueryDTO;
import com.marvels.financial.pay.hjpay.dto.DirectPaymentQueryResultDTO;
import com.marvels.financial.pay.hjpay.dto.DirectPaymentResultDTO;
import com.marvels.financial.pay.hjpay.dto.DirectPaymentSmsDTO;
import com.marvels.financial.pay.hjpay.dto.LoanPaymentCallBackDTO;
import com.marvels.financial.pay.hjpay.dto.MerchantRechargePayDTO;
import com.marvels.financial.pay.hjpay.dto.PaymentCallBackDTO;
import com.marvels.financial.pay.hjpay.dto.SinglePaymentDTO;
import com.marvels.financial.pay.hjpay.dto.SinglePaymentQueryDTO;
import com.marvels.financial.pay.hjpay.dto.SinglePaymentQueryResultDTO;
import com.marvels.financial.pay.hjpay.dto.SinglePaymentResultDTO;
import com.marvels.financial.pay.hjpay.service.HjPayApi;
import com.marvels.system.common.dao.McsmRevealConfigureAppDao;
import com.marvels.system.common.dto.McsmRevealConfigureAppDTO;

import cn.hutool.core.util.StrUtil;

/**
 * 汇聚支付服务
 * @author 唐佩文
 *
 */
@Service
public class HjPayImpl implements HjPayApi{

	@Value("${config.properties.path}")
	private  String configPropertiesPath;
	@Autowired
	private McsmRevealConfigureAppDao mcsmRevealConfigureAppDao;
	
	@Autowired
	private McfePaymentWithholdDetailDao detailDao;
	

	@Autowired
	private WithholdPaymentApi withholdPaymentApi;

	@Autowired
	private McfeCustomerLoanContractDao contractDao;

	@Autowired
	private McfeLendingProcessDao mcfeLendingProcessMapper;

	@Autowired
	private McfePaymentWithholdDao withholdDao;

	@Autowired
	private FinancialConsumerLoanApplyApi consumerLoanApplyApi;
	
	@Autowired
	private LoanPaymentApi loanPaymentApi;
	
	@Autowired
	private LoanAuditApi loanAuditApi;
	
	@Autowired
	private FinancialConsumerApproveApi consumerApproveApi;
	
	@Autowired
	private McfeRepaymentTradeDetailsMapper mcamRepaymentTradeDetailsMapper;
	
	@Autowired
	private McfeMerchantRechargeRecordMapper mcfeMerchantRechargeRecordMapper;
	@Override
	public Map<String, Object> singlePayment(SinglePaymentDTO singlePaymentDTO) throws MarvelsBusinessException {
		if(StringUtils.isEmpty(singlePaymentDTO.getMerchantOrderNo())){
			throw new MarvelsBusinessException("商户订单号不能为空");
		}
		if(StringUtils.isEmpty(singlePaymentDTO.getReceiverAccountNoEnc())){
			throw new MarvelsBusinessException("收款人银行卡卡号不能为空");
		}
		if(StringUtils.isEmpty(singlePaymentDTO.getReceiverNameEnc())){
			throw new MarvelsBusinessException("收款人银行卡持卡人名称不能为空");
		}
		if(StringUtils.isEmpty(singlePaymentDTO.getPaidAmount())){
			throw new MarvelsBusinessException("交易金额不能为空");
		}
		if(StringUtils.isEmpty(singlePaymentDTO.getPaidDesc())){
			throw new MarvelsBusinessException("代付说明不能为空");
		}
		String merchantNo  = gethjMerchantNo();
		Map<String,Object> map=new LinkedHashMap<String,Object>();
		map.put("userNo", merchantNo);//商户编号
		String productCode  = ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.productCode");
		singlePaymentDTO.setProductCode(productCode);
		String firstProductCode  = ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.firstProductCode");
		singlePaymentDTO.setFirstProductCode(firstProductCode);
		//代付回调地址
		String hjPaymentCallBackUrl= ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.payment.callback.url");
		if(StringUtils.isNotEmpty(hjPaymentCallBackUrl)){
			singlePaymentDTO.setCallbackUrl(hjPaymentCallBackUrl);
		}
		//将参数对象转成map
		singlePaymentDTO.setPaidAmount(String.valueOf(new BigDecimal(singlePaymentDTO.getPaidAmount()).setScale(2, BigDecimal.ROUND_HALF_UP)));
		map=BeanUtils.object2Map(map,singlePaymentDTO);
		map.put("hmac",this.ybHmac(map));//签名
		//开始请求
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚单笔代付请求参数:"+com.alibaba.fastjson.JSONObject.toJSONString(map));
		String url=ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.singlePay.url");
		String resultParams="";
		Map<String, Object> result=new LinkedHashMap<String, Object>();
		try {
			resultParams=HttpUtils.httpPost(url,com.alibaba.fastjson.JSONObject.toJSONString(map).toString());
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>receiverAccountNoEnc"+singlePaymentDTO.getReceiverAccountNoEnc()+",汇聚单笔代付请求异常:",e);
			result.put("errorcode",MarvelsConstant.PROCESSING);
			result.put("errormsg","单笔代付接口请求异常");
			return result;
		}
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚单笔代付返回参数:"+resultParams);
		com.alibaba.fastjson.JSONObject resultJson=JSON.parseObject(resultParams);
		String statusCode=resultJson.getString("statusCode");
		String  message =resultJson.getString("message");
		if(statusCode.equalsIgnoreCase("2001")){//响应成功
			com.alibaba.fastjson.JSONObject dataJson=resultJson.getJSONObject("data");//应答数据
			Map<String,Object> linkMap=new LinkedHashMap<String, Object>();
			linkMap.put("statusCode", statusCode);
			linkMap.put("message", message);
			String returnYbHmac=ybHmac(BeanUtils.object2Map(linkMap,JSON.parseObject(dataJson.toString(), SinglePaymentResultDTO.class)));
			if(returnYbHmac.equalsIgnoreCase(dataJson.getString("hmac"))){//验签一致
				String  errorCode =dataJson.getString("errorCode");
				String  errorDesc =dataJson.getString("errorDesc");
				if(StringUtils.isNotEmpty(errorCode) && !"300002011".equals(errorCode)){//errorCode不为空且不是反回订单号已存在则置为交易失败
					result.put("status",MarvelsConstant.FAILED);
					result.put("errormsg",errorDesc);
				}else{
					result.put("status",MarvelsConstant.PROCESSING);
					result.put("errormsg",errorDesc);
				}
			}else{
				result.put("status",MarvelsConstant.FAILED);
				result.put("errormsg","验签不一致");
			}
		}else if(statusCode.equalsIgnoreCase("2002")){
			result.put("status",MarvelsConstant.FAILED);
			result.put("errormsg",message);
		}else{//其余都做处理中
			result.put("status",MarvelsConstant.PROCESSING);
			result.put("errormsg",message);
		}
		result.put("errorcode",statusCode);
		MarvelsLogUtil.getInstance().info(">>>>>>>>receiverAccountNoEnc"+singlePaymentDTO.getReceiverAccountNoEnc()+",汇聚单笔代付map:"+com.alibaba.fastjson.JSONObject.toJSONString(result));
		return result;
	}

	
	
	
	
	
	
	/**
	 * 易宝加签
	 */
	public String ybHmac(Map<String, Object> map){
		List<String> keys = new ArrayList<String>(map.keySet());
		String requestParams ="";
		for(int i=0;i<keys.size();i++) {
			String key = keys.get(i);
			Object value = map.get(key);// 强制类型转换
			if(!key.equalsIgnoreCase("hmac") && map.get(key)!=null){
				requestParams = requestParams+value;
			}
		}
		String primaryKey = gethjPrimaryKey();
		requestParams=requestParams+primaryKey;
		MarvelsLogUtil.getInstance().info(">>>>加签之前数据:"+requestParams);
		return DigestUtils.md5Hex(requestParams).toUpperCase();
	}







	@Override
	public Map<String, Object> singlePaymentQuery(SinglePaymentQueryDTO singlePaymentQueryDTO)
			throws MarvelsBusinessException {
		if(StringUtils.isEmpty(singlePaymentQueryDTO.getMerchantOrderNo())){
			throw new MarvelsBusinessException("商户订单号不能为空");
		}
		String merchantNo  = gethjMerchantNo();
		Map<String,Object> map=new LinkedHashMap<String,Object>();
		map.put("userNo", merchantNo);//商户编号
		//将参数对象转成map
		map=BeanUtils.object2Map(map,singlePaymentQueryDTO);
		map.put("hmac",this.ybHmac(map));//签名
		//开始请求
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚单笔代付结果查询请求参数:"+com.alibaba.fastjson.JSONObject.toJSONString(map));
		String url=ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.singlePayQuery.url");
		String resultParams="";
		Map<String, Object> result=new LinkedHashMap<String, Object>();
		try {
			resultParams=HttpUtils.httpPost(url,com.alibaba.fastjson.JSONObject.toJSONString(map));
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>merchantOrderNo"+singlePaymentQueryDTO.getMerchantOrderNo()+",汇聚单笔代付结果查询请求异常:",e);
			result.put("errorcode",MarvelsConstant.PROCESSING);
			result.put("errormsg","单笔代付结果查询接口请求异常");
			return result;
		}
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚单笔代付结果查询返回参数:"+resultParams);
		com.alibaba.fastjson.JSONObject resultJson=JSON.parseObject(resultParams);
		String statusCode=resultJson.getString("statusCode");
		String  message =resultJson.getString("message");
		if(statusCode.equalsIgnoreCase("2001")){//响应成功
			com.alibaba.fastjson.JSONObject dataJson=resultJson.getJSONObject("data");//应答数据
			Map<String,Object> linkMap=new LinkedHashMap<String, Object>();
			linkMap.put("statusCode", statusCode);
			linkMap.put("message", message);
			String returnYbHmac=ybHmac(BeanUtils.object2Map(linkMap,JSON.parseObject(dataJson.toString(), SinglePaymentQueryResultDTO.class)));
			if(returnYbHmac.equalsIgnoreCase(dataJson.getString("hmac"))){//验签一致
				String  errorDesc =dataJson.getString("errorDesc");
				String status=dataJson.getString("status");
				if("205".equals(status)){
					result.put("status",MarvelsConstant.SUCCESS);
					result.put("errormsg","成功");
				}else if("208".equals(status) || "204".equals(status) || "214".equals(status)){//订单已取消 交易失败 订单不存在
					result.put("status",MarvelsConstant.FAILED);
					result.put("errormsg",errorDesc);
				}else{
					result.put("status",MarvelsConstant.PROCESSING);
					result.put("errormsg",errorDesc);
				}
			}else{
				result.put("status",MarvelsConstant.FAILED);
				result.put("errormsg","验签不一致");
			}
		}else if(statusCode.equalsIgnoreCase("2002")){
			result.put("status",MarvelsConstant.FAILED);
			result.put("errormsg",message);
		}else{//其余都做处理中
			result.put("status",MarvelsConstant.PROCESSING);
			result.put("errormsg",message);
		}
		result.put("errorcode",statusCode);
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚单笔代付结果查询map:"+com.alibaba.fastjson.JSONObject.toJSONString(result));
		return result;
	}







	@Override
	public Map<String, Object> agreementPaymentSms(AgreementPaymentSmsDTO agreementPaymentSmsDTO)
			throws MarvelsBusinessException {
		if(StringUtils.isEmpty(agreementPaymentSmsDTO.getQ1_OrderNo())){
			throw new MarvelsBusinessException("商户订单号不能为空");
		}
		if(StringUtils.isEmpty(agreementPaymentSmsDTO.getS1_PayerName())){
			throw new MarvelsBusinessException("支付人姓名不能为空");
		}
		if(StringUtils.isEmpty(agreementPaymentSmsDTO.getS3_PayerCardNo())){
			throw new MarvelsBusinessException("支付人证件号不能为空");
		}
		if(StringUtils.isEmpty(agreementPaymentSmsDTO.getS4_PayerBankCardNo())){
			throw new MarvelsBusinessException("银行卡号码不能为空");
		}
		if(StringUtils.isEmpty(agreementPaymentSmsDTO.getS7_BankMobile())){
			throw new MarvelsBusinessException("预留手机号不能为空");
		}
		String merchantNo  = gethjMerchantNo();
		String merchantName  = ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.merchant.name");
		agreementPaymentSmsDTO.setP1_MerchantNo(merchantNo);
		agreementPaymentSmsDTO.setP2_MerchantName(merchantName);
		Map<String,Object> map=new LinkedHashMap<String,Object>();
		//将参数对象转成map
		map=BeanUtils.object2Map(map,agreementPaymentSmsDTO);
		map.put("hmac",this.ybHmac(map));//签名
		//开始请求
		MarvelsLogUtil.getInstance().info(">>>>>>>>快捷支付-协议支付短信请求参数:"+com.alibaba.fastjson.JSONObject.toJSONString(map));
		String url=ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.agreement.payment.sms.url");
		String resultParams="";
		Map<String, Object> result=new LinkedHashMap<String, Object>();
		try {
			resultParams=HttpUtils.sendHttpPost(url,map);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>q1_OrderNo"+agreementPaymentSmsDTO.getQ1_OrderNo()+",快捷支付-协议支付短信请求异常:",e);
			result.put("errorcode",MarvelsConstant.FAILED);
			result.put("errormsg","快捷支付-协议支付短信请求异常");
			result.put("status","BIND_FAIL");
			return result;
		}
		MarvelsLogUtil.getInstance().info(">>>>>>>>快捷支付-协议支付短信返回参数:"+resultParams);
		com.alibaba.fastjson.JSONObject resultJson=JSON.parseObject(resultParams);
		String raStatus=resultJson.getString("ra_Status");
		String  rbMsg =resultJson.getString("rb_Msg");
		String returnYbHmac=ybHmac(BeanUtils.object2Map(new LinkedHashMap<String, Object>(),JSON.parseObject(resultParams, AgreementPaymentSmsResultDTO.class)));
		if(returnYbHmac.equalsIgnoreCase(resultJson.getString("hmac"))){//验签一致
			if(raStatus.equalsIgnoreCase("100")){//发送成功
				result.put("errormsg","成功");
				result.put("status","TO_VALIDATE");//沿用易宝的预绑卡订单状态  TO_VALIDATE  待短验
			}else{//其余都做失败处理
				result.put("errormsg",rbMsg);
				result.put("status","BIND_FAIL");
			}
			if(raStatus.equalsIgnoreCase("100") || raStatus.equalsIgnoreCase("101") || raStatus.equalsIgnoreCase("102") ){
				result.put("r5_TrxNo",resultJson.getString("r5_TrxNo"));//支付平台流水号
			}
		}else{
			result.put("errormsg","验签不一致");
			result.put("status","BIND_FAIL");
		}
		result.put("errorcode",raStatus);
		MarvelsLogUtil.getInstance().info(">>>>>>>>快捷支付-协议支付短信接口map:"+com.alibaba.fastjson.JSONObject.toJSONString(result));
		return result;
	}







	@Override
	public Map<String, Object> agreementPaymentSign(AgreementPaymentSignDTO agreementPaymentSignDTO)
			throws MarvelsBusinessException {
		if(StringUtils.isEmpty(agreementPaymentSignDTO.getQ1_OrderNo())){
			throw new MarvelsBusinessException("商户订单号不能为空");
		}
		if(StringUtils.isEmpty(agreementPaymentSignDTO.getS1_PayerName())){
			throw new MarvelsBusinessException("支付人姓名不能为空");
		}
		if(StringUtils.isEmpty(agreementPaymentSignDTO.getS3_PayerCardNo())){
			throw new MarvelsBusinessException("支付人证件号不能为空");
		}
		if(StringUtils.isEmpty(agreementPaymentSignDTO.getS4_PayerBankCardNo())){
			throw new MarvelsBusinessException("银行卡号码不能为空");
		}
		if(StringUtils.isEmpty(agreementPaymentSignDTO.getS7_BankMobile())){
			throw new MarvelsBusinessException("预留手机号不能为空");
		}
		if(StringUtils.isEmpty(agreementPaymentSignDTO.getT2_SmsCode())){
			throw new MarvelsBusinessException("短信验证码不能为空");
		}
		String merchantNo  = gethjMerchantNo();
		String merchantName  = ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.merchant.name");
		agreementPaymentSignDTO.setP1_MerchantNo(merchantNo);
		agreementPaymentSignDTO.setP2_MerchantName(merchantName);
		Map<String,Object> map=new LinkedHashMap<String,Object>();
		//将参数对象转成map
		map=BeanUtils.object2Map(map,agreementPaymentSignDTO);
		map.put("hmac",this.ybHmac(map));//签名
		//开始请求
		MarvelsLogUtil.getInstance().info(">>>>>>>>快捷支付-协议支付签约接口请求参数:"+com.alibaba.fastjson.JSONObject.toJSONString(map));
		String url=ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.agreement.payment.sign.url");
		String resultParams="";
		Map<String, Object> result=new LinkedHashMap<String, Object>();
		try {
			resultParams=HttpUtils.sendHttpPost(url,map);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>q1_OrderNo"+agreementPaymentSignDTO.getQ1_OrderNo()+",快捷支付-协议支付签约请求异常:",e);
			result.put("errorcode",MarvelsConstant.PROCESSING);
			result.put("errormsg","快捷支付-协议支付签约请求异常");
			return result;
		}
		MarvelsLogUtil.getInstance().info(">>>>>>>>快捷支付-协议支付签约接口返回参数:"+resultParams);
		com.alibaba.fastjson.JSONObject resultJson=JSON.parseObject(resultParams);
		String raStatus=resultJson.getString("ra_Status");
		String  rbMsg =resultJson.getString("rb_Msg");
		String returnYbHmac=ybHmac(BeanUtils.object2Map(new LinkedHashMap<String, Object>(),JSON.parseObject(resultParams, AgreementPaymentSignResultDTO.class)));
		if(returnYbHmac.equalsIgnoreCase(resultJson.getString("hmac"))){//验签一致
			if(raStatus.equalsIgnoreCase("100")){//签约成功
				result.put("errormsg","成功");
				String signedId=resultJson.getString("signedId");//商户签约 ID   商户用于下次请求支付时使用，成功必返回
				result.put("signedId",signedId);
				result.put("status","BIND_SUCCESS");
			}else{//其余都做失败处理
				result.put("errormsg",rbMsg);
				result.put("status","BIND_FAIL");
			}
		}else{
			result.put("errormsg","验签不一致");
			result.put("status","BIND_FAIL");
		}
		result.put("errorcode",raStatus);
		MarvelsLogUtil.getInstance().info(">>>>>>>>快捷支付-协议支付短信签约接口map:"+com.alibaba.fastjson.JSONObject.toJSONString(result));
		return result;
	} 
	
	
	
	public static void main(String[] args) {
		String s="{\"data\":{\"status\":\"205\",\"errorCode\":\"\",\"errorDesc\":\"\",\"userNo\":\"888105300000877\",\"merchantOrderNo\":\"HJXYDF154459140054178957\",\"platformSerialNo\":\"300318121230481136\",\"receiverAccountNoEnc\":\"6217002870020942361\",\"receiverNameEnc\":\"林小娜\",\"paidAmount\":0.20,\"fee\":0.50,\"hmac\":\"1f093b7eeb30d557efb85b50649a5328\"},\"statusCode\":2001,\"message\":\"受理成功\"}";
		com.alibaba.fastjson.JSONObject resultJson=JSON.parseObject(s);
		String statusCode=resultJson.getString("statusCode");
		String  message =resultJson.getString("message");
		Map<String,Object> linkMap=new LinkedHashMap<String, Object>();
		linkMap.put("statusCode", statusCode);
		linkMap.put("message", message);
		SinglePaymentQueryResultDTO dto=JSON.parseObject(resultJson.getJSONObject("data").toString(), SinglePaymentQueryResultDTO.class);
		BeanUtils.object2Map(linkMap,dto);
		List<String> keys3 = new ArrayList<String>(linkMap.keySet());
		String requestParams3 ="";
		for(int i=0;i<keys3.size();i++) {
			String key = keys3.get(i);
			Object value = linkMap.get(key);//String.valueOf( 强制类型转换
			if(!key.equalsIgnoreCase("hmac") && linkMap.get(key)!=null){
				requestParams3 = requestParams3+value;
			}
		}
		String primaryKey="9c662b388978492cb264e48ae50b74a9";
		requestParams3=requestParams3+primaryKey;
		System.out.println(DigestUtils.md5Hex(requestParams3).toUpperCase());
		System.out.println(com.alibaba.fastjson.JSONObject.toJSONString(linkMap));
		System.out.println(DigestUtils.md5Hex("2001查询成功888105300000877深圳云科谷信息服务有限公司2010.000.000.009c662b388978492cb264e48ae50b74a9").toUpperCase());
		
		
		MerchantRechargeCallBackDTO merchantRechargeCallBackDTO =new MerchantRechargeCallBackDTO();
		merchantRechargeCallBackDTO=JSON.parseObject("{\"hmac\":\"3acb9a517b514dfac440bb0f62507d0a\",\"r1_MerchantNo\":\"888105300000877\",\"r2_OrderNo\":\"HJWXCZ154477823381831088\",\"r3_Amount\":\"0.01\",\"r4_Cur\":\"1\",\"r5_Mp\":\"\",\"r6_Status\":\"100\",\"r7_TrxNo\":\"100218121469981181\",\"r8_BankOrderNo\":\"100218121469981181\",\"r9_BankTrxNo\":\"CEECEP01165033021514_0\",\"ra_PayTime\":\"2018-12-14+16%3A57%3A38\",\"rb_DealTime\":\"2018-12-14+16%3A57%3A38\",\"rc_BankCode\":\"ABC\"}",MerchantRechargeCallBackDTO.class);
		Map<String,Object> map=new LinkedHashMap<String,Object>();
		map=BeanUtils.object2Map(map,merchantRechargeCallBackDTO);
		for(String key:map.keySet()){
			map.put(key, URLDecoder.decode(String.valueOf(map.get(key))));
		}
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚充值回调解码后数据:"+com.alibaba.fastjson.JSONObject.toJSONString(map));
		List<String> keys1 = new ArrayList<String>(map.keySet());
		String requestParams1 ="";
		for(int i=0;i<keys1.size();i++) {
			String key = keys1.get(i);
			Object value = map.get(key);//String.valueOf( 强制类型转换
			if(!key.equalsIgnoreCase("hmac") && map.get(key)!=null){
				requestParams1 = requestParams1+value;
			}
		}
		requestParams1=requestParams1+primaryKey;
		System.out.println(requestParams1);
		System.out.println(DigestUtils.md5Hex(requestParams1).toUpperCase());
	}



	@Override
	public Map<String, Object> agreementPayment(AgreementPaymentDTO agreementPaymentDTO)
			throws MarvelsBusinessException {
		// TODO Auto-generated method stub
		if(StringUtils.isEmpty(agreementPaymentDTO.getQ1_OrderNo())){
			throw new MarvelsBusinessException("商户订单号不能为空");
		}
		if(agreementPaymentDTO.getQ2_Amount()==null){
			throw new MarvelsBusinessException("订单金额不能为空");
		}
		if(StringUtils.isEmpty(agreementPaymentDTO.getQ4_ProductName())){
			throw new MarvelsBusinessException("商品名称不能为空");
		}
		if(StringUtils.isEmpty(agreementPaymentDTO.getS9_bankSignId()) && StringUtils.isEmpty(agreementPaymentDTO.getS4_PayerBankCardNo())){
			throw new MarvelsBusinessException("银行卡号码不能为空或者签约id必须有一个不能为空");
		}
		String merchantNo  = gethjMerchantNo();
		String merchantName  = ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.merchant.name");
		String notifyUrl  = ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.agreement.payment.notify.url");
		agreementPaymentDTO.setP1_MerchantNo(merchantNo);
		agreementPaymentDTO.setP2_MerchantName(merchantName);
		agreementPaymentDTO.setQ7_NotifyUrl(notifyUrl);
		agreementPaymentDTO.setQ2_Amount(agreementPaymentDTO.getQ2_Amount().setScale(2, BigDecimal.ROUND_HALF_UP));
		Map<String,Object> map=new LinkedHashMap<String,Object>();
		//将参数对象转成map
		map=BeanUtils.object2Map(map,agreementPaymentDTO);
		map.put("hmac",this.ybHmac(map));//签名
		//开始请求
		MarvelsLogUtil.getInstance().info(">>>>>>>>快捷支付-协议支付接口请求参数:"+com.alibaba.fastjson.JSONObject.toJSONString(map));
		String url=ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.agreement.payment.url");
		String resultParams="";
		Map<String, Object> result=new LinkedHashMap<String, Object>();
		try {
			resultParams=HttpUtils.sendHttpPost(url,map);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>q1_OrderNo"+agreementPaymentDTO.getQ1_OrderNo()+",快捷支付-协议支付请求异常:",e);
			result.put("errorcode",MarvelsConstant.PROCESSING);
			result.put("errormsg","快捷支付-协议支付请求异常");
			return result;
		}
		MarvelsLogUtil.getInstance().info(">>>>>>>>快捷支付-协议支付接口返回参数:"+resultParams);
		String raStatus = "";
		if(StrUtil.isEmpty(resultParams)){
			result.put("status", MarvelsConstant.PROCESSING);
			result.put("errormsg", "处理中");
		}else{
			com.alibaba.fastjson.JSONObject resultJson=JSON.parseObject(resultParams);
			raStatus=resultJson.getString("ra_Status");
			String  rbMsg =resultJson.getString("rb_Msg");
			String returnYbHmac=ybHmac(BeanUtils.object2Map(new LinkedHashMap<String, Object>(),JSON.parseObject(resultParams, AgreementPaymentResultDTO.class)));
			if(returnYbHmac.equalsIgnoreCase(resultJson.getString("hmac"))){//验签一致
				if (raStatus.equalsIgnoreCase("100") || raStatus.equalsIgnoreCase("102")
						|| raStatus.equalsIgnoreCase("10080000") || raStatus.equalsIgnoreCase("10080066")
						|| raStatus.equalsIgnoreCase("20070021") || raStatus.equalsIgnoreCase("CP000008")
						|| raStatus.equalsIgnoreCase("CP000028") || raStatus.equalsIgnoreCase("CP000032")
						|| raStatus.equalsIgnoreCase("CP100017")) {// 接口请求成功 做处理中处理
					result.put("status", MarvelsConstant.PROCESSING);
					result.put("errormsg", "处理中");
				}
//				else if(raStatus.equalsIgnoreCase("101")){//失败
//					result.put("status",MarvelsConstant.FAILED);
//					result.put("errormsg",rbMsg);
//				}
				else{//其余都是失败  101 或异常状态
					result.put("status",MarvelsConstant.FAILED);
					result.put("errormsg",rbMsg);
				}
				result.put("r5_TrxNo",resultJson.get("r5_TrxNo"));
			}else{
				result.put("status",MarvelsConstant.FAILED);
				result.put("errormsg","验签不一致");
			}
		}
		result.put("errorcode",raStatus);
		MarvelsLogUtil.getInstance().info(">>>>>>>>协议代扣map:"+com.alibaba.fastjson.JSONObject.toJSONString(result));
		return result;
	}







	@Override
	public Map<String, Object> agreementPaymentQuery(AgreementPaymentQueryDTO agreementPaymentQueryDTO)
			throws MarvelsBusinessException {
		if(StringUtils.isEmpty(agreementPaymentQueryDTO.getP2_OrderNo())){
			throw new MarvelsBusinessException("商户订单号不能为空");
		}
		String merchantNo  = gethjMerchantNo();
		Map<String,Object> map=new LinkedHashMap<String,Object>();
		map.put("p1_MerchantNo", merchantNo);//商户编号
		//将参数对象转成map
		map=BeanUtils.object2Map(map,agreementPaymentQueryDTO);
		map.put("hmac",this.ybHmac(map));//签名
		//开始请求
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚快捷支付-协议代扣结果查询请求参数:"+com.alibaba.fastjson.JSONObject.toJSONString(map));
		String url=ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.agreement.payment.query.url");
		String resultParams="";
		Map<String, Object> result=new LinkedHashMap<String, Object>();
		try {
			resultParams=HttpUtils.sendHttpPost(url,map);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>订单号p2_OrderNo"+agreementPaymentQueryDTO.getP2_OrderNo()+",协议代扣结果查询请求异常:",e);
			result.put("errorcode",MarvelsConstant.PROCESSING);
			result.put("errormsg","协议代扣结果查询请求异常");
			return result;
		}
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚快捷支付-协议代扣结果查询返回参数:"+resultParams);
		com.alibaba.fastjson.JSONObject resultJson=JSON.parseObject(resultParams);
		String raStatus=String.valueOf(resultJson.get("ra_Status"));
		String  rcCodeMsg =String.valueOf(resultJson.get("rc_CodeMsg"));
		String rbCode=String.valueOf(resultJson.get("rb_Code"));
		if(rbCode.equalsIgnoreCase("100")){//正常
			String returnYbHmac=ybHmac(BeanUtils.object2Map(new LinkedHashMap<String, Object>(),JSON.parseObject(resultParams, AgreementPaymentQueryResultDTO.class)));
			if(returnYbHmac.equalsIgnoreCase(resultJson.getString("hmac"))){//验签一致
				if(raStatus.equalsIgnoreCase("100")){//交易成功
					result.put("status",MarvelsConstant.SUCCESS);
					result.put("errormsg","成功");
				}else if(raStatus.equalsIgnoreCase("101")){//失败
					result.put("status",MarvelsConstant.FAILED);
					result.put("errormsg",rcCodeMsg);
				}else{//其余都做处理中处理
					result.put("status",MarvelsConstant.PROCESSING);
					result.put("errormsg",rcCodeMsg);
				}
				result.put("r5_TrxNo",resultJson.get("r5_TrxNo"));
			}else{
				result.put("status",MarvelsConstant.FAILED);
				result.put("errormsg","验签不一致");
			}
		}else{
			result.put("status",MarvelsConstant.FAILED);
			result.put("errormsg",rcCodeMsg);
		}
		result.put("errorcode",raStatus);
		MarvelsLogUtil.getInstance().info(">>>>>>>>协议代扣结果查询map:"+com.alibaba.fastjson.JSONObject.toJSONString(result));
		return result;
	}





	@Override
	public Map<String, Object> directPayment(DirectPaymentDTO directPaymentDTO) throws MarvelsBusinessException {
		if(StringUtils.isEmpty(directPaymentDTO.getQ1_OrderNo())){
			throw new MarvelsBusinessException("商户订单号不能为空");
		}
		if(StringUtils.isEmpty(directPaymentDTO.getS1_PayerName())){
			throw new MarvelsBusinessException("支付人姓名不能为空");
		}
		if(StringUtils.isEmpty(directPaymentDTO.getS3_PayerCardNo())){
			throw new MarvelsBusinessException("支付人证件号不能为空");
		}
		if(StringUtils.isEmpty(directPaymentDTO.getS4_PayerBankCardNo())){
			throw new MarvelsBusinessException("银行卡号码不能为空");
		}
		if(StringUtils.isEmpty(directPaymentDTO.getS7_BankMobile())){
			throw new MarvelsBusinessException("预留手机号不能为空");
		}
		if(directPaymentDTO.getQ2_Amount()==null){
			throw new MarvelsBusinessException("订单金额不能为空");
		}
		if(StringUtils.isEmpty(directPaymentDTO.getQ4_ProductName())){
			throw new MarvelsBusinessException("商品名称不能为空");
		}
		if(StringUtils.isEmpty(directPaymentDTO.getT2_SmsCode())){
			throw new MarvelsBusinessException("短信验证码不能为空");
		}
		String merchantNo  = gethjMerchantNo();
		String merchantName  = ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.merchant.name");
		String notifyUrl  = ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.agreement.payment.notify.url");
		directPaymentDTO.setP1_MerchantNo(merchantNo);
		directPaymentDTO.setP2_MerchantName(merchantName);
		directPaymentDTO.setQ7_NotifyUrl(notifyUrl);
		directPaymentDTO.setQ2_Amount(directPaymentDTO.getQ2_Amount().setScale(2, BigDecimal.ROUND_HALF_UP));
		Map<String,Object> map=new LinkedHashMap<String,Object>();
		//将参数对象转成map
		map=BeanUtils.object2Map(map,directPaymentDTO);
		map.put("hmac",this.ybHmac(map));//签名
		//开始请求
		MarvelsLogUtil.getInstance().info(">>>>>>>>快捷支付-直接代扣接口请求参数:"+com.alibaba.fastjson.JSONObject.toJSONString(map));
		String url=ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.direct.payment.url");
		String resultParams="";
		Map<String, Object> result=new LinkedHashMap<String, Object>();
		try {
			resultParams=HttpUtils.sendHttpPost(url,map);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>q1_OrderNo"+directPaymentDTO.getQ1_OrderNo()+",快捷支付-直接代扣请求异常:",e);
			result.put("errorcode",MarvelsConstant.PROCESSING);
			result.put("errormsg","快捷支付-直接代扣请求异常");
			return result;
		}
		MarvelsLogUtil.getInstance().info(">>>>>>>>快捷支付-直接代扣接口返回参数:"+resultParams);
		com.alibaba.fastjson.JSONObject resultJson=JSON.parseObject(resultParams);
		String raStatus=resultJson.getString("ra_Status");
		String  rbMsg =resultJson.getString("rb_Msg");
		String returnYbHmac=ybHmac(BeanUtils.object2Map(new LinkedHashMap<String, Object>(),JSON.parseObject(resultParams, DirectPaymentResultDTO.class)));
		if(returnYbHmac.equalsIgnoreCase(resultJson.getString("hmac"))){//验签一致
			if (raStatus.equalsIgnoreCase("100") || raStatus.equalsIgnoreCase("102")
					|| raStatus.equalsIgnoreCase("10080000") || raStatus.equalsIgnoreCase("10080066")
					|| raStatus.equalsIgnoreCase("20070021") || raStatus.equalsIgnoreCase("CP000008")
					|| raStatus.equalsIgnoreCase("CP000028") || raStatus.equalsIgnoreCase("CP000032")
					|| raStatus.equalsIgnoreCase("CP100017")) {// 接口请求成功 做处理中处理
				result.put("status", MarvelsConstant.PROCESSING);
				result.put("errormsg", "处理中");
			}else{//其余都是失败  101 或异常状态
				result.put("status",MarvelsConstant.FAILED);
				result.put("errormsg",rbMsg);
			}
			result.put("r5_TrxNo",resultJson.get("r5_TrxNo"));
		}else{
			result.put("status",MarvelsConstant.FAILED);
			result.put("errormsg","验签不一致");
		}
		result.put("errorcode",raStatus);
		MarvelsLogUtil.getInstance().info(">>>>>>>>直接支付map:"+com.alibaba.fastjson.JSONObject.toJSONString(result));
		return result;
	}







	@Override
	public Map<String, Object> directPaymentQuery(DirectPaymentQueryDTO directPaymentQueryDTO)
			throws MarvelsBusinessException {
		if(StringUtils.isEmpty(directPaymentQueryDTO.getP2_OrderNo())){
			throw new MarvelsBusinessException("商户订单号不能为空");
		}
		String merchantNo  = gethjMerchantNo();
		Map<String,Object> map=new LinkedHashMap<String,Object>();
		map.put("p1_MerchantNo", merchantNo);//商户编号
		//将参数对象转成map
		map=BeanUtils.object2Map(map,directPaymentQueryDTO);
		map.put("hmac",this.ybHmac(map));//签名
		//开始请求
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚支付-直接代扣结果查询请求参数:"+com.alibaba.fastjson.JSONObject.toJSONString(map));
		String url=ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.direct.payment.query.url");
		String resultParams="";
		Map<String, Object> result=new LinkedHashMap<String, Object>();
		try {
			resultParams=HttpUtils.sendHttpPost(url,map);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>订单号p2_OrderNo"+directPaymentQueryDTO.getP2_OrderNo()+",直接代扣结果查询请求异常:",e);
			result.put("errorcode",MarvelsConstant.PROCESSING);
			result.put("errormsg","直接代扣结果查询请求异常");
			return result;
		}
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚支付-直接代扣结果查询返回参数:"+resultParams);
		com.alibaba.fastjson.JSONObject resultJson=JSON.parseObject(resultParams);
		String raStatus=String.valueOf(resultJson.get("ra_Status"));
		String  rcCodeMsg =String.valueOf(resultJson.get("rc_CodeMsg"));
		String rbCode=String.valueOf(resultJson.get("rb_Code"));
		if(rbCode.equalsIgnoreCase("100")){//正常
			String returnYbHmac=ybHmac(BeanUtils.object2Map(new LinkedHashMap<String, Object>(),JSON.parseObject(resultParams, DirectPaymentQueryResultDTO.class)));
			if(returnYbHmac.equalsIgnoreCase(resultJson.getString("hmac"))){//验签一致
				if(raStatus.equalsIgnoreCase("100")){//交易成功
					result.put("status",MarvelsConstant.SUCCESS);
					result.put("errormsg","成功");
				}else if(raStatus.equalsIgnoreCase("101")){//失败
					result.put("status",MarvelsConstant.FAILED);
					result.put("errormsg",rcCodeMsg);
				}else{//其余都做处理中处理
					result.put("status",MarvelsConstant.PROCESSING);
					result.put("errormsg",rcCodeMsg);
				}
				result.put("r5_TrxNo",resultJson.get("r5_TrxNo"));
			}else{
				result.put("status",MarvelsConstant.FAILED);
				result.put("errormsg","验签不一致");
			}
		}else{
			result.put("status",MarvelsConstant.FAILED);
			result.put("errormsg",rcCodeMsg);
		}
		result.put("errorcode",raStatus);
		MarvelsLogUtil.getInstance().info(">>>>>>>>直接支付结果查询map:"+com.alibaba.fastjson.JSONObject.toJSONString(result));
		return result;
	}



	@Override
	public Map<String, Object> merchantRecharge(MerchantRechargePayDTO merchantRechargeDTO) throws MarvelsBusinessException{
		if (StringUtils.isEmpty(merchantRechargeDTO.getP2_OrderNo())) {
			throw new MarvelsBusinessException("商户订单号不能为空");
		}
		if (merchantRechargeDTO.getP3_Amount() == null) {
			throw new MarvelsBusinessException("订单金额不能为空");
		}
		if (StringUtils.isEmpty(merchantRechargeDTO.getP5_ProductName())) {
			throw new MarvelsBusinessException("商品名称不能为空");
		}
		merchantRechargeDTO.setP3_Amount(merchantRechargeDTO.getP3_Amount().setScale(2, BigDecimal.ROUND_HALF_UP));
		String merchantNo = gethjMerchantNo();
		merchantRechargeDTO.setP1_MerchantNo(merchantNo);
		String returnUrl = ServerProperties.getValue(configPropertiesPath, "common.properties",
				"hj.merchant.recharge.returnUrl");
		merchantRechargeDTO.setP7_ReturnUrl(returnUrl);
		String notifyUrl = ServerProperties.getValue(configPropertiesPath, "common.properties",
				"hj.merchant.recharge.notifyUrl");
		merchantRechargeDTO.setP8_NotifyUrl(notifyUrl);
		Map<String, Object> map = new LinkedHashMap<String, Object>();
		// 将参数对象转成map
		map = BeanUtils.object2Map(map, merchantRechargeDTO);
		String hmac = this.ybHmac(map);// 签名
		map.put("hmac", hmac);
		String requestUrl = ServerProperties.getValue(configPropertiesPath, "common.properties",
				"hj.merchant.recharge.url");
		// 拼装html
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder
//				.append("<html lang='en'>").append("<head>").append("<meta charset='UTF-8'>")
//				.append("<meta name='Generator' content='EditPlus'>").append("<meta name='Author' content=''>")
//				.append("<meta name='Keywords' content=''>").append("<meta name='Description' content=''>")
//				.append("<title>Document</title>").append("</head>").append("<body>")
				.append("<form action='")
				.append(requestUrl).append("'  id='gateway'").append(" method='post'>");
		for (String key : map.keySet()) {
			Object value = org.springframework.util.StringUtils.isEmpty(map.get(key)) ? "" : map.get(key);
			if (key.equals("p5_ProductName")) {
				try {
					URLEncoder.encode(String.valueOf(value), "UTF-8");
				} catch (UnsupportedEncodingException e) {
					MarvelsLogUtil.getInstance().error(">>>>>>>>商户充值encode失败:", e);
				}
			}
			stringBuilder.append("<input type='hidden' name='").append(key).append("' value='").append(value)
					.append("'>");
		}
		stringBuilder.append("</form>");
//				.append("<script type='text/javascript'>document.getElementById('gateway').submit();</script>")
//				.append("</body>").append("</html>");
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("appendHtml", stringBuilder.toString());
		return dataMap;
	}







	@Override
	public Map<String, Object> hjMerchantRechargeCallBack(MerchantRechargeCallBackDTO merchantRechargeCallBackDTO)  throws MarvelsBusinessException{
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚充值回调参数:"+com.alibaba.fastjson.JSONObject.toJSONString(merchantRechargeCallBackDTO));
		Map<String,Object> map=new LinkedHashMap<String,Object>();
		map=BeanUtils.object2Map(map,merchantRechargeCallBackDTO);
		for(String key:map.keySet()){
			map.put(key, URLDecoder.decode(String.valueOf(map.get(key))));
		}
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚充值回调解码后数据:"+com.alibaba.fastjson.JSONObject.toJSONString(map));
		String returnYbHmac=ybHmac(map);
		if(!merchantRechargeCallBackDTO.getHmac().equalsIgnoreCase(returnYbHmac)){
			throw new MarvelsBusinessException("验签不一致");
		}
		String status=merchantRechargeCallBackDTO.getR6_Status();
		String result="";
		if("100".equals(status)){//交易成功
			result="0";
		}else if("101".equals(status) || "103".equals(status)){//失败
			result="-1";
		}else{
			result="0";
		}
		McfeMerchantRechargeRecordDTO dto=new McfeMerchantRechargeRecordDTO();
		dto.setResult(result);
		dto.setCode(merchantRechargeCallBackDTO.getR6_Status());
		dto.setPayPlatOrderNumber(merchantRechargeCallBackDTO.getR8_BankOrderNo());
		dto.setPayPlatReqNo(merchantRechargeCallBackDTO.getR7_TrxNo());
		dto.setBankTrxNo(merchantRechargeCallBackDTO.getR9_BankTrxNo());
		dto.setPayTime(String.valueOf(map.get("ra_PayTime")));
		dto.setOrderNumber(merchantRechargeCallBackDTO.getR2_OrderNo());
		UserDTO user=null;
		try {
			user = CacheUtils.getCacheUser();
		} catch (MarvelsBusinessException e) {
			
		}
		String userCode=user==null?"system":user.getUserCode();
		dto.setUpdatedDate(new Date());
		dto.setUpdatedBy(userCode);
		int i=mcfeMerchantRechargeRecordMapper.udateByOrderNumber(dto);
		if(i<1){
			throw new MarvelsBusinessException("更新商户充值记录失败");
		}
		Map<String, Object> dataMap=new HashMap<>();
		dataMap.put("status", result);
		return dataMap;
	}







	@Override
	public Map<String, Object> merchantBalance()
			throws MarvelsBusinessException {
		String merchantNo  = gethjMerchantNo();
		Map<String,Object> map=new LinkedHashMap<String,Object>();
		map.put("userNo", merchantNo);//商户编号
		map.put("hmac",this.ybHmac(map));//签名
		//开始请求
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚商户余额查询请求参数:"+com.alibaba.fastjson.JSONObject.toJSONString(map));
		String url=ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.available.balance.url");
		String resultParams="";
		Map<String, Object> result=new LinkedHashMap<String, Object>();
		try {
			resultParams=HttpUtils.httpPost(url,com.alibaba.fastjson.JSONObject.toJSONString(map).toString());
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>汇聚商户余额查询:",e);
			result.put("errorcode",MarvelsConstant.PROCESSING);
			result.put("errormsg","汇聚商户余额查询请求异常");
			return result;
		}
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚商户余额查询返回参数:"+resultParams);
		com.alibaba.fastjson.JSONObject resultJson=JSON.parseObject(resultParams);
		String statusCode=resultJson.getString("statusCode");
		String  message =resultJson.getString("message");
		if(statusCode.equalsIgnoreCase("2001")){//响应成功
			com.alibaba.fastjson.JSONObject dataJson=resultJson.getJSONObject("data");//应答数据
			Map<String,Object> linkMap=new LinkedHashMap<String, Object>();
			linkMap.put("statusCode", statusCode);
			linkMap.put("message", message);
			String returnYbHmac=ybHmac(BeanUtils.object2Map(linkMap,JSON.parseObject(dataJson.toString(), AvailableBalanceResultDTO.class)));
			if(returnYbHmac.equalsIgnoreCase(dataJson.getString("hmac"))){//验签一致
				String  errorCode =dataJson.getString("errorCode");
				String  errorDesc =dataJson.getString("errorDesc");
				if(StringUtils.isNotEmpty(errorCode) && !"300002011".equals(errorCode)){//errorCode不为空且不是反回订单号已存在则置为交易失败
					result.put("status",MarvelsConstant.FAILED);
					result.put("errormsg",errorDesc);
				}else{
					result.putAll(linkMap);
					Map<String, Object> desirableMap=merchantBalanceDesirable();
					result.put("useAbleSettAmount",desirableMap.get("useAbleSettAmount"));
					result.put("availableSettAmountFrozen",desirableMap.get("availableSettAmountFrozen"));
				}
			}else{
				result.put("status",MarvelsConstant.FAILED);
				result.put("errormsg","验签不一致");
			}
		}else if(statusCode.equalsIgnoreCase("2002")){
			result.put("status",MarvelsConstant.FAILED);
			result.put("errormsg",message);
		}else{//其余都做处理中
			result.put("status",MarvelsConstant.PROCESSING);
			result.put("errormsg",message);
		}
		result.put("errorcode",statusCode);
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚商户余额查询map:"+com.alibaba.fastjson.JSONObject.toJSONString(result));
		return result;
	}
	
	/**
	 * 商户可取余额查询
	 * @return
	 * @throws MarvelsBusinessException
	 */
	public Map<String, Object> merchantBalanceDesirable()
			throws MarvelsBusinessException {
		String merchantNo  = gethjMerchantNo();
		Map<String,Object> map=new LinkedHashMap<String,Object>();
		map.put("userNo", merchantNo);//商户编号
		map.put("hmac",this.ybHmac(map));//签名
		//开始请求
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚商户可取余额查询请求参数:"+com.alibaba.fastjson.JSONObject.toJSONString(map));
		String url=ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.available.balance.url.desirable");
		String resultParams="";
		Map<String, Object> result=new LinkedHashMap<String, Object>();
		try {
			resultParams=HttpUtils.httpPost(url,com.alibaba.fastjson.JSONObject.toJSONString(map).toString());
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>汇聚商户可取余额查询查询:",e);
			result.put("errorcode",MarvelsConstant.PROCESSING);
			result.put("errormsg","汇聚商户余额查询请求异常");
			return result;
		}
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚商户可取余额查询返回参数:"+resultParams);
		com.alibaba.fastjson.JSONObject resultJson=JSON.parseObject(resultParams);
		String statusCode=resultJson.getString("statusCode");
		String  message =resultJson.getString("message");
		if(statusCode.equalsIgnoreCase("2001")){//响应成功
			com.alibaba.fastjson.JSONObject dataJson=resultJson.getJSONObject("data");//应答数据
			Map<String,Object> linkMap=new LinkedHashMap<String, Object>();
			linkMap.put("statusCode", statusCode);
			linkMap.put("message", message);
			String returnYbHmac=ybHmac(BeanUtils.object2Map(linkMap,JSON.parseObject(dataJson.toString(), AvailableBalanceResultDesirableDTO.class)));
			if(returnYbHmac.equalsIgnoreCase(dataJson.getString("hmac"))){//验签一致
				String  errorCode =dataJson.getString("errorCode");
				String  errorDesc =dataJson.getString("errorDesc");
				if(StringUtils.isNotEmpty(errorCode) && !"300002011".equals(errorCode)){//errorCode不为空且不是反回订单号已存在则置为交易失败
					result.put("status",MarvelsConstant.FAILED);
					result.put("errormsg",errorDesc);
				}else{
					result.putAll(linkMap);
				}
			}else{
				result.put("status",MarvelsConstant.FAILED);
				result.put("errormsg","验签不一致");
			}
		}else if(statusCode.equalsIgnoreCase("2002")){
			result.put("status",MarvelsConstant.FAILED);
			result.put("errormsg",message);
		}else{//其余都做处理中
			result.put("status",MarvelsConstant.PROCESSING);
			result.put("errormsg",message);
		}
		result.put("errorcode",statusCode);
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚商户可取余额查询map:"+com.alibaba.fastjson.JSONObject.toJSONString(result));
		return result;
	}
	
	
	private String gethjMerchantNo(){
		String merchantNo = null;
		McsmRevealConfigureAppDTO config = mcsmRevealConfigureAppDao.queryConfigByKey("hj.merchantno");
		if(config != null && config.getConfigValue() != null && config.getState() == 0){
			merchantNo = config.getConfigValue();
		}
		MarvelsLogUtil.getInstance().info("实时获取汇聚商户号：" + merchantNo);
		return merchantNo;
	}

	private String gethjPrimaryKey(){
		String merchantNo = null;
		McsmRevealConfigureAppDTO config = mcsmRevealConfigureAppDao.queryConfigByKey("hj.merchant.primarykey");
		if(config != null && config.getConfigValue() != null && config.getState() == 0){
			merchantNo = config.getConfigValue();
		}
		MarvelsLogUtil.getInstance().info("实时获取汇聚秘钥：" + merchantNo);
		return merchantNo;
	}







	@Override
	public Map<String, Object> directPaymentSms(DirectPaymentSmsDTO directPaymentSmsDTO)
			throws MarvelsBusinessException {
		if(StringUtils.isEmpty(directPaymentSmsDTO.getQ1_OrderNo())){
			throw new MarvelsBusinessException("商户订单号不能为空");
		}
		if(directPaymentSmsDTO.getQ2_Amount()==null){
			throw new MarvelsBusinessException("订单金额不能为空");
		}
		if(StringUtils.isEmpty(directPaymentSmsDTO.getS1_PayerName())){
			throw new MarvelsBusinessException("支付人姓名不能为空");
		}
		if(StringUtils.isEmpty(directPaymentSmsDTO.getS3_PayerCardNo())){
			throw new MarvelsBusinessException("支付人证件号不能为空");
		}
		if(StringUtils.isEmpty(directPaymentSmsDTO.getS4_PayerBankCardNo())){
			throw new MarvelsBusinessException("支付人银行卡号不能为空");
		}
		if(StringUtils.isEmpty(directPaymentSmsDTO.getS7_BankMobile())){
			throw new MarvelsBusinessException("银行预留手机号不能为空");
		}
		String merchantNo  = gethjMerchantNo();
		String merchantName  = ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.merchant.name");
		String notifyUrl  = ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.agreement.payment.notify.url");
		directPaymentSmsDTO.setP1_MerchantNo(merchantNo);
		directPaymentSmsDTO.setP2_MerchantName(merchantName);
		directPaymentSmsDTO.setQ7_NotifyUrl(notifyUrl);
		directPaymentSmsDTO.setQ2_Amount(directPaymentSmsDTO.getQ2_Amount().setScale(2, BigDecimal.ROUND_HALF_UP));
		Map<String,Object> map=new LinkedHashMap<String,Object>();
		//将参数对象转成map
		map=BeanUtils.object2Map(map,directPaymentSmsDTO);
		map.put("hmac",this.ybHmac(map));//签名
		//开始请求
		MarvelsLogUtil.getInstance().info(">>>>>>>>快捷 支付--短信接口请求参数:"+com.alibaba.fastjson.JSONObject.toJSONString(map));
		String url=ServerProperties.getValue(configPropertiesPath, "common.properties", "hj.direct.payment.sms.url");
		String resultParams="";
		Map<String, Object> result=new LinkedHashMap<String, Object>();
		try {
			resultParams=HttpUtils.sendHttpPost(url,map);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>q1_OrderNo"+directPaymentSmsDTO.getQ1_OrderNo()+",快捷 支付--短信接口请求异常:",e);
			result.put("errorcode",MarvelsConstant.PROCESSING);
			result.put("errormsg","快捷 支付--短信接口请求异常");
			return result;
		}
		MarvelsLogUtil.getInstance().info(">>>>>>>>快捷 支付--短信接口接口返回参数:"+resultParams);
		com.alibaba.fastjson.JSONObject resultJson=JSON.parseObject(resultParams);
		String raStatus=resultJson.getString("ra_Status");
		String  rbMsg =resultJson.getString("rb_Msg");
		String returnYbHmac=ybHmac(BeanUtils.object2Map(new LinkedHashMap<String, Object>(),JSON.parseObject(resultParams, DirectPaymentResultDTO.class)));
		if(returnYbHmac.equalsIgnoreCase(resultJson.getString("hmac"))){//验签一致
			if(raStatus.equalsIgnoreCase("100")){//交易成功
				result.put("status",MarvelsConstant.SUCCESS);
				result.put("errormsg","成功");
			}else{//失败   raStatus.equalsIgnoreCase("101")
				result.put("status",MarvelsConstant.FAILED);
				result.put("errormsg",rbMsg);
			}
			result.put("r5_TrxNo",resultJson.get("r5_TrxNo"));
		}else{
			result.put("status",MarvelsConstant.FAILED);
			result.put("errormsg","验签不一致");
		}
		result.put("errorcode",raStatus);
		MarvelsLogUtil.getInstance().info(">>>>>>>>快捷 支付--短信接口map:"+com.alibaba.fastjson.JSONObject.toJSONString(result));
		return result;
	}







	@Override
	public void ybPaymentNotify(PaymentCallBackDTO callBackDTO) throws MarvelsBusinessException {
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚支付回调参数:"+com.alibaba.fastjson.JSONObject.toJSONString(callBackDTO));
		Map<String,Object> map=new LinkedHashMap<String,Object>();
		map=BeanUtils.object2Map(map,callBackDTO);
		for(String key:map.keySet()){
			map.put(key, URLDecoder.decode(String.valueOf(map.get(key))));
		}
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚支付回调解码后数据:"+com.alibaba.fastjson.JSONObject.toJSONString(map));
		String returnYbHmac=ybHmac(map);
		if(!callBackDTO.getHmac().equalsIgnoreCase(returnYbHmac)){
			throw new MarvelsBusinessException("验签不一致");
		}
		this.callBackDeal(map);
	}
	
	private void callBackDeal(Map<String,Object> map) throws MarvelsBusinessException {
		String batchName = Thread.currentThread().getId() + "-" + UUID.randomUUID().toString().replace("-", "");
		// 先将交易结果处于处理中的代扣流水详情占用
		int count = detailDao.occupationOrder(batchName,String.valueOf(map.get("r2_OrderNo")));
		if (count < 1) {
			MarvelsLogUtil.getInstance().info(">>>>>汇聚支付回调订单号:" + String.valueOf(map.get("r2_OrderNo")) + ",占用订单号失败");
			throw new MarvelsBusinessException("占用订单号失败");
		}
		String status = String.valueOf(map.get("r6_Status"));
		String result = "";
		if ("100".equals(status)) {// 交易成功
			result = "2";
		} else if ("101".equals(status)) {// 失败
			result = "9";
		}
		// 查询出被该批次号占用的代扣流水详情
		List<McfePaymentWithholdDetailDTO> listDTO = detailDao.selectByBatchName(batchName);
		for (McfePaymentWithholdDetailDTO detailDTO : listDTO) {
			String loanId = detailDTO.getLoanId();
			// 查询合同状态
			McfeCustomerLoanContractDTO contractDTO = contractDao.selectContractByLoanId(loanId);
			if (contractDTO.getStatus() != 0 && contractDTO.getStatus() != 1) {
				MarvelsLogUtil.getInstance().info(">>>>>>>>>>loanId:" + loanId + "查询代扣状态时,合同状态不处于还款中");
				McfePaymentWithholdDetailDTO detailDTOUpdate = new McfePaymentWithholdDetailDTO();
				detailDTOUpdate.setId(detailDTO.getId());
				detailDTOUpdate.setUpdatedBy("SYSTEM");
				detailDTOUpdate.setUpdatedDate(new Date());
				detailDTOUpdate.setBatchStatus("2");// 将批次状态改成处理完成
				detailDao.updateByPrimaryKeySelective(detailDTOUpdate);
				continue;
			}
			McfePaymentWithholdDTO withholdDTO = withholdDao.selectByWithholdCode(detailDTO.getWithholdCode());
			if (null == withholdDTO) {
				MarvelsLogUtil.getInstance().info(">>>>>>>>>>loanId:" + loanId + "查询代扣流水无记录");
				McfePaymentWithholdDetailDTO detailDTOUpdate = new McfePaymentWithholdDetailDTO();
				detailDTOUpdate.setId(detailDTO.getId());
				detailDTOUpdate.setUpdatedBy("SYSTEM");
				detailDTOUpdate.setUpdatedDate(new Date());
				detailDTOUpdate.setBatchStatus("2");// 将批次状态改成处理完成
				detailDao.updateByPrimaryKeySelective(detailDTOUpdate);
				continue;
			}
			McfeRepaymentTradeDetails mcamRepaymentTradeDetails = mcamRepaymentTradeDetailsMapper.selectByOrderNum(String.valueOf(map.get("r2_OrderNo")));
			if(mcamRepaymentTradeDetails == null){
				throw new MarvelsBusinessException("交易记录不存在");
			}
			String tradeResult = mcamRepaymentTradeDetails.getResult();
			if("0".equals(tradeResult) || "-3".equals(tradeResult) || "-4".equals(result) || "-1".equals(tradeResult)){
				throw new MarvelsBusinessException("交易记录状态不处于交易中");
			}
			if(StringUtils.isNotEmpty(status) && status.equals("100")){
				mcamRepaymentTradeDetails.setSuccessTime(DateUtils.getDateStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
			}
			mcamRepaymentTradeDetails.setPayNumReturn(String.valueOf(map.get("r2_OrderNo")));
			mcamRepaymentTradeDetails.setResult(status.equals("100")?MarvelsConstant.SUCCESS:MarvelsConstant.FAILED);
			mcamRepaymentTradeDetails.setErrorCode(status);
			mcamRepaymentTradeDetails.setErrorMsg(String.valueOf(map.get("re_ErrMsg")));
			mcamRepaymentTradeDetailsMapper.updateByPrimaryKeySelective(mcamRepaymentTradeDetails);
			// 更新代扣流水
			McfePaymentWithholdDetailDTO detailDTOUpdate = new McfePaymentWithholdDetailDTO();
			detailDTOUpdate.setId(detailDTO.getId());
			detailDTOUpdate.setUpdatedBy("SYSTEM");
			detailDTOUpdate.setUpdatedDate(new Date());
			detailDTOUpdate.setStatus(result);// 1交易中; 2代扣成功 9代扣失败
			detailDTOUpdate.setRtnOrderNo(String.valueOf(map.get("r2_OrderNo")));
			String paymentChannel = ServerProperties.getValue(configPropertiesPath, "common.properties",
					"payment_channel");
			detailDTOUpdate.setResChannel(paymentChannel);
			detailDTOUpdate.setRtnResponseDate(new Date());
			detailDTOUpdate.setBatchStatus("2");// 将批次状态改成处理完成
			detailDTOUpdate.setRtnResponseCode(status);// 扣款返回码
			detailDTOUpdate.setRtnResponseMsg(String.valueOf(map.get("re_ErrMsg")));// 扣款返回信息
			if ("2".equals(result)) {// 成功
				detailDTOUpdate.setAmountAct(detailDTO.getAmount());
			}
			detailDao.updateByPrimaryKeySelective(detailDTOUpdate);
			if ("2".equals(result)) {// 成功
				detailDTOUpdate.setTransctionSeq(detailDTO.getTransctionSeq());
				try {
					MarvelsLogUtil.getInstance().info(">>>>>>>>>>>>>>loanId" + loanId +"汇聚代扣回调结果为成功处理开始");
					withholdDTO.setRepayStyle(withholdDTO.getPayType() + "");
					withholdDTO.setFlowPayType("1");
					withholdPaymentApi.withholdSuccess(contractDTO, withholdDTO, detailDTOUpdate);
				} catch (Exception e) {
					MarvelsLogUtil.getInstance().error(">>>>>>代扣成功处理异常:", e);
				}
			}
			// 更新代扣总记录
			McfePaymentWithholdDTO withholdDTOUpdate = new McfePaymentWithholdDTO();
			withholdDTOUpdate.setId(withholdDTO.getId());
			BigDecimal successAmount = new BigDecimal("0");
			if ("2".equals(result)) {// 成功
				successAmount = detailDTO.getAmount();
			}
			// 查询代扣详情表中的处理中的数据
			int countFail = detailDao.countDealingByWithholdCode(detailDTO.getWithholdCode());
			BigDecimal amountAct = (withholdDTO.getAmountAct() == null ? BigDecimal.ZERO : withholdDTO.getAmountAct())
					.add(successAmount);
			if (withholdDTO.getAmount().doubleValue() <= amountAct.doubleValue()) {
				withholdDTOUpdate.setStatus("1");// 代扣成功
			} else if (countFail > 0) {
				withholdDTOUpdate.setStatus("2");// 代扣中
			} else {
				withholdDTOUpdate.setStatus("9");// 代扣失败
			}
			withholdDTOUpdate.setUpdatedBy("SYSTEM");
			withholdDTOUpdate.setUpdatedDate(new Date());
			withholdDTOUpdate.setAmountAct(amountAct);
			withholdDao.updateByPrimaryKeySelective(withholdDTOUpdate);
			MarvelsLogUtil.getInstance().info(">>>>>>>>>>>>>>loanId" + loanId +"汇聚代扣回调回调处理成功");
		}
	}







	@Override
	public void hjPaymentCallBack(LoanPaymentCallBackDTO callBackDTO) throws MarvelsBusinessException {
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚代付结果异步回调参数:"+com.alibaba.fastjson.JSONObject.toJSONString(callBackDTO));
		Map<String,Object> map=new LinkedHashMap<String,Object>();
		map=BeanUtils.object2Map(map,callBackDTO);
		for(String key:map.keySet()){
			map.put(key, URLDecoder.decode(String.valueOf(map.get(key))));
		}
		MarvelsLogUtil.getInstance().info(">>>>>>>>汇聚代付结果异步回调解码后数据:"+com.alibaba.fastjson.JSONObject.toJSONString(map));
		String returnYbHmac=ybHmac(map);
		if(!callBackDTO.getHmac().equalsIgnoreCase(returnYbHmac)){
			throw new MarvelsBusinessException("验签不一致");
		}
		//代付异步回调结果处理
		this.paymentCallBackDeal(map);
	}
	
	/**
	 * 代付异步回调结果处理
	 * @param callBackDTO
	 * @throws MarvelsBusinessException
	 */
	private void paymentCallBackDeal(Map<String,Object> map) throws MarvelsBusinessException{
		long threadId = Thread.currentThread().getId();
		MarvelsLogUtil.getInstance().info(">>>>>>>>>>线程号:" + threadId + "汇聚代付结果异步回调参数开始");
		// 先锁住一批需要放款的数据
		String batName = threadId + UUID.randomUUID().toString().replace("-", "");
		String orderNumber=String.valueOf(map.get("merchantOrderNo"));
		int count = mcfeLendingProcessMapper.updateAuditInfo(batName, String.valueOf(threadId), "F10",null,orderNumber);// 支付中
		if (count < 1) {// 订单号不处于查询状态
			MarvelsLogUtil.getInstance().info(">>>>>汇聚代付结果异步回调订单号:" + orderNumber + ",占用订单号失败");
			throw new MarvelsBusinessException("占用订单号失败");
		}
		// 查询出当前批次锁住的需要放款的数据
		List<McfeLendingProcess> list = mcfeLendingProcessMapper.selectByBatName(batName, String.valueOf(threadId),"F10");
		if (list != null && list.size() > 0) {
			for (McfeLendingProcess mcfeLendingProcess : list) {
				String loanId = mcfeLendingProcess.getLoanId();
				MarvelsLogUtil.getInstance().info(">>>>>>>>>>线程号:" + threadId + ",loanId" + loanId + "汇聚代付结果异步回调处理开始");
				McamLoanApplyInfoDTO mcamLoanApplyInfo = new McamLoanApplyInfoDTO();
				mcamLoanApplyInfo.setLoanId(loanId);
				McamLoanApplyInfoDTO mcamLoanApplyInfoDTO = consumerApproveApi.selectLoanApplyInfo(mcamLoanApplyInfo);
				if (!"F03".equalsIgnoreCase(mcamLoanApplyInfoDTO.getStatus())) {// 先判断该笔放款在进件表中是否处于待放款状态
					MarvelsLogUtil.getInstance()
							.info(">>>>>>>>>>>>>>loanId" + loanId + ",手动放款的放款时进件表状态:" + mcamLoanApplyInfoDTO.getStatus());
					continue;
				}
				String status=String.valueOf(map.get("status"));
				// 0成功 -1失败 1交易处理中
				String auditStatus = "";
				String auditMsg =String.valueOf(map.get("errorCodeDesc"));
				McfeRepaymentTradeDetails mcamRepaymentTradeDetails = mcamRepaymentTradeDetailsMapper.selectByOrderNum(orderNumber);
				if(mcamRepaymentTradeDetails == null){
					throw new MarvelsBusinessException("交易记录不存在");
				}
				String result = mcamRepaymentTradeDetails.getResult();
				if("0".equals(result) || "-3".equals(result) || "-4".equals(result) || "-1".equals(result)){
					throw new MarvelsBusinessException("交易记录状态不处于交易中");
				}
				if(StringUtils.isNotEmpty(status) && status.equals("205")){
					mcamRepaymentTradeDetails.setSuccessTime(DateUtils.getDateStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
				}
				mcamRepaymentTradeDetails.setPayNumReturn(orderNumber);
				mcamRepaymentTradeDetails.setResult(status.equals("205")?MarvelsConstant.SUCCESS:MarvelsConstant.FAILED);
				mcamRepaymentTradeDetails.setErrorCode(status);
				mcamRepaymentTradeDetails.setErrorMsg(auditMsg);
				mcamRepaymentTradeDetailsMapper.updateByPrimaryKeySelective(mcamRepaymentTradeDetails);
				if("205".equals(status)){//成功
					//放款成功
					auditStatus = "F2";
					//新增 ac_loan_apply_info 	money_hand_out_uid
					try {
						MarvelsLogUtil.getInstance().info(">>>>>>>>>>>>>>loanId" + loanId +"汇聚代付结果异步回调结果为成功处理开始");
						McfeLendingProcess process = new McfeLendingProcess();
						String reloanFlag =  consumerLoanApplyApi.synchroMoneyHandOutTime(loanId);
						process.setReloanFlag(reloanFlag);
						process.setLoanId(loanId);
						mcfeLendingProcessMapper.updateAuditResult(process);
					} catch (Exception e) {
						MarvelsLogUtil.getInstance().error(">>>>>>>>>>loanId:" + loanId + "同步到进件表的放款时间失败:", e);
					}
					loanPaymentApi.loanSuccessDeal(mcfeLendingProcess);
				}else if("204".equals(status)){
					auditStatus = "F3";
				}else{//其他状态码不做处理   异步回调只有成功失败
					throw new MarvelsBusinessException("代付结果异步回调状态异常");
				}
				
				//记录放款日志
				loanAuditApi.auditCommonDeal(loanId, auditStatus, mcfeLendingProcess.getStatus(), "放款异步回调", null);
				// 持久化审核信息
				McfeLendingProcess process = new McfeLendingProcess();
				process.setLoanId(loanId);
				process.setMsg( auditMsg);
				process.setStatus(auditStatus);
				if("F2".equals(auditStatus)){
					//自动放款成功
					process.setPassTime(new Date());
					//新增 ac_loan_apply_info 	money_hand_out_uid
					try {
						String reloanFlag =  consumerLoanApplyApi.synchroMoneyHandOutTime(loanId);
						process.setReloanFlag(reloanFlag);
					} catch (Exception e) {
						MarvelsLogUtil.getInstance().error(">>>>>>>>>>loanId:" + loanId + "同步到进件表的放款时间失败:", e);
					}
				}
				process.setUpdatedBy("system");
				process.setOriginalStatus(mcfeLendingProcess.getStatus());
				process.setLoanId(loanId);
				process.setIsBusy("0");// 将审核状态改为空闲
				int countInsert = mcfeLendingProcessMapper.updateAuditResult(process);
				if (countInsert < 1) {
					MarvelsLogUtil.getInstance().info(">>>>>>>>>>>>>>loanId" + loanId + ",持久化审核信息失败");
					throw new MarvelsBusinessException("代付结果查询持久化审核信息失败");
				}
				MarvelsLogUtil.getInstance().info(">>>>>>>>>>>>>>loanId" + loanId +"汇聚代付结果异步回调处理成功");
			}
		}
	}
}
